package cn.cttic.order.controller;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.cttic.base.api.RemoteBaseDeviceInfoService;
import cn.cttic.base.api.domain.vo.BaseDeviceInfoVo;
import cn.cttic.common.core.utils.BeanCopyUtils;
import cn.cttic.order.api.domain.bo.*;
import cn.cttic.order.api.domain.vo.*;
import cn.cttic.order.service.IBaseInstallOrderProcessService;
import cn.cttic.order.service.IBaseSaleOrderService;
import cn.hutool.core.util.ObjectUtil;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.cttic.common.idempotent.annotation.RepeatSubmit;
import cn.cttic.common.log.annotation.Log;
import cn.cttic.common.web.core.BaseController;
import cn.cttic.common.mybatis.core.page.PageQuery;
import cn.cttic.common.core.domain.R;
import cn.cttic.common.core.validate.AddGroup;
import cn.cttic.common.core.validate.EditGroup;
import cn.cttic.common.log.enums.BusinessType;
import cn.cttic.common.excel.utils.ExcelUtil;
import cn.cttic.order.service.IBaseInstallOrderService;
import cn.cttic.common.mybatis.core.page.TableDataInfo;

/**
 * 安装订单
 * 前端访问路由地址为:/order/installOrder
 *
 * @author Times.Studio
 * @date 2024-09-17
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/installOrder")
public class BaseInstallOrderController extends BaseController {

    private final IBaseInstallOrderService baseInstallOrderService;

    private final IBaseSaleOrderService baseSaleOrderService;

    private final IBaseInstallOrderProcessService baseInstallOrderProcessService;

    /**
     * 分页查询订单列表
     *
     * @param bo        查询参数
     * @param pageQuery 分页参数
     * @return
     */
    @SaCheckPermission("order:installOrder:list")
    @GetMapping("/list")
    public TableDataInfo<BaseInstallOrderVo> list(BaseInstallOrderQueryBo bo, PageQuery pageQuery) {
        return baseInstallOrderService.queryPageList(bo, pageQuery);
    }

    /**
     * 分页查询已经提交安装的订单列表
     *
     * @param bo        查询参数
     * @param pageQuery 分页参数
     * @return
     */
    @GetMapping(value = "/getInstalledOrderlist")
    public TableDataInfo<BaseInstallOrderVo> getInstalledOrderlist(BaseInstallOrderQueryBo bo, PageQuery pageQuery) {
        return baseInstallOrderService.queryInstalledPageList(bo, pageQuery);
    }

    /**
     * 签收订单（内业数据制作/验收）
     *
     * @param bo 签收参数
     * @return
     */
    @PostMapping(value = "/receiveInstalledOrder")
    public R<?> receiveInstalledOrder(@RequestBody @Valid ReceiveOrderBo bo) {
        try {
            BaseInstallOrderVo vo = baseInstallOrderService.receiveInstalledOrder(bo.getOrderId());
            return R.ok(vo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.fail("签收订单失败");
        }
    }

    /**
     * 分页查询个人签收的订单列表（用于验收）
     *
     * @param bo        查询参数
     * @param pageQuery 分页参数
     * @return
     */
    @GetMapping(value = "/getReceivedPageList")
    public TableDataInfo<BaseInstallOrderVo> getReceivedPageList(BaseInstallOrderQueryBo bo, PageQuery pageQuery) {
        return baseInstallOrderService.queryReceivedPageList(bo, pageQuery);
    }

    /**
     * 新增安装订单
     */
    @RepeatSubmit()
    @PostMapping("/verify")
    public R<BaseInstallOrderVo> verify(@Validated @RequestBody VerifyOrderBo bo) {
        try {
            BaseInstallOrderVo vo = baseInstallOrderService.verifyOrder(bo);
            return R.ok(vo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.fail(ex.getMessage());
        }
    }

    //---------------- 安装单 质控 -----------------------------------------------------------------------------------
    // 开始

    /**
     * 分页查询已经验收通过的订单列表
     *
     * @param bo        查询参数
     * @param pageQuery 分页参数
     * @return
     */
    @GetMapping(value = "/getVerifiedOrderList")
    public TableDataInfo<BaseInstallOrderVo> getVerifiedOrderList(BaseInstallOrderQueryBo bo, PageQuery pageQuery) {
        return baseInstallOrderService.queryVerifiedPageList(bo, pageQuery);
    }

    /**
     * 签收订单（订单质控 QC）
     *
     * @param bo 签收参数
     * @return
     */
    @PostMapping(value = "/receiveVerifiedOrder")
    public R<?> receiveVerifiedOrder(@RequestBody @Valid ReceiveOrderBo bo) {
        try {
            BaseInstallOrderVo vo = baseInstallOrderService.receiveVerifiedOrder(bo.getOrderId());
            return R.ok(vo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.fail("签收订单失败");
        }
    }

    /**
     * 分页查询个人签收的订单列表（用于验收）
     *
     * @param bo        查询参数
     * @param pageQuery 分页参数
     * @return
     */
    @GetMapping(value = "/getReceived4ReviewPageList")
    public TableDataInfo<BaseInstallOrderVo> getReceived4ReviewPageList(BaseInstallOrderQueryBo bo, PageQuery pageQuery) {
        return baseInstallOrderService.queryReceived4ReviewPageList(bo, pageQuery);
    }

    /**
     * 新增安装订单
     */
    @RepeatSubmit()
    @PostMapping("/reviewVerifiedOrder")
    public R<BaseInstallOrderVo> reviewVerifiedOrder(@Validated @RequestBody ReviewOrderBo bo) {
        try {
            BaseInstallOrderVo vo = baseInstallOrderService.reviewVerifiedOrder(bo);
            return R.ok(vo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.fail(ex.getMessage());
        }
    }

    // 结束
    //---------------- 安装单 质控 -----------------------------------------------------------------------------------


    @GetMapping(value = "/getCheckPageList")
    public TableDataInfo<BaseInstallOrderVo> getCheckPageList(BaseInstallOrderQueryBo bo, PageQuery pageQuery) {
        return baseInstallOrderService.queryCheckPageList(bo, pageQuery);
    }

    /**
     * 获取订单详情（用于验收）
     *
     * @param orderId 安装订单ID
     * @return
     */
    @GetMapping(value = "/getDetail")
    public R<?> getDetail(@RequestParam(name = "orderId", defaultValue = "1") String orderId) {
        InstallOrderVerifyVo vo  = baseInstallOrderService.queryVerifyDetailById(orderId);
        return R.ok(vo);
    }

    /**
     * 导出安装订单列表
     */
    @SaCheckPermission("order:installOrder:export")
    @Log(title = "安装订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BaseInstallOrderQueryBo bo, HttpServletResponse response) {
        List<BaseInstallOrderVo> list = baseInstallOrderService.queryList(bo);
        ExcelUtil.exportExcel(list, "安装订单", BaseInstallOrderVo.class, response);
    }

    /**
     * 重置订单
     */
    @RepeatSubmit()
    @PostMapping("/reset")
    public R<BaseInstallOrderVo> reset(@Validated @RequestBody OrderQueryBaseBo bo) {
        try {
            BaseInstallOrderVo vo = baseInstallOrderService.resetOrder(bo.getOrderId());
            return R.ok(vo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.fail(ex.getMessage());
        }
    }

    /**
     * 新增安装订单
     */
    @RepeatSubmit()
    @PostMapping("/check")
    public R<BaseInstallOrderVo> check(@Validated @RequestBody VerifyOrderBo bo) {
        try {
            BaseInstallOrderVo vo = baseInstallOrderService.checkOrder(bo);
            return R.ok(vo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.fail(ex.getMessage());
        }
    }

    /**
     * 获取安装订单详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("order:installOrder:query")
    @GetMapping("/{id}")
    public R<BaseInstallOrderVo> getInfo(@NotNull(message = "主键不能为空")
                                         @PathVariable String id) {
        return R.ok(baseInstallOrderService.queryById(id));
    }

    /**
     * 新增安装订单
     */
    @SaCheckPermission("order:installOrder:add")
    @Log(title = "安装订单", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BaseInstallOrderBo bo) {
        return toAjax(baseInstallOrderService.insertByBo(bo));
    }

    /**
     * 修改安装订单
     */
    @SaCheckPermission("order:installOrder:edit")
    @Log(title = "安装订单", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BaseInstallOrderBo bo) {
        return toAjax(baseInstallOrderService.updateByBo(bo));
    }

    /**
     * 删除安装订单
     *
     * @param ids 主键串
     */
    @SaCheckPermission("order:installOrder:remove")
    @Log(title = "安装订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(baseInstallOrderService.deleteWithValidByIds(List.of(ids), true));
    }
}
